package com.google.samples.apps.paging.http;

import androidx.annotation.NonNull;

import java.util.HashMap;
import java.util.Iterator;

public class HttpBody extends HashMap<String, Object> {

    @Override
    public Object put(String key, Object value) {
        return super.put(key, value);
    }

    public HttpBody add(String key, Object v) {
        put(key, v);
        return this;
    }

    public HttpBody addAll(HttpBody body) {
        body.putAll(body);
        return body;
    }

    @NonNull
    @Override
    public String toString() {
        return toJson();
    }

    public String toJson() {
        Iterator<Entry<String, Object>> i = entrySet().iterator();
        if (!i.hasNext())
            return "{}";

        StringBuilder sb = new StringBuilder();
        sb.append('{');


        for (; ; ) {
            Entry<String, Object> e = i.next();
            String key = e.getKey();
            Object value = e.getValue();
            sb.append("\"" + key + "\"");
//            sb.append(key == this ? "(this Map)" : "\"" + key + "\"");
            sb.append(':');
            if (value instanceof Integer || value instanceof Long) {
                sb.append(value == this ? "(this Map)" : value);
            } else {
                sb.append(value == this ? "(this Map)" : "\"" + value + "\"");
            }
            if (!i.hasNext())
                return sb.append('}').toString();
            sb.append(',').append(' ');
        }
    }

    /**
     * 默认添加UserId
     *
     * @return
     */
    public static HttpBody getBody() {
        HttpBody httpBody = new HttpBody();
//        String userId = AppData.Companion.getUserId();
//        if (AppData.Companion.isLogin())
//            httpBody.add(Constants.Companion.getBUNDLE_USER_ID(), userId);
//        if (AppData.Companion.isBusinessPage()) {
//            httpBody.add(Constants.Companion.getBUNDLE_SHOP_ID(), AppData.Companion.getShopId());
//        }
        return httpBody;
    }

    /**
     * @return
     */
    public static HttpBody getBody(boolean isAddUserId) {
        HttpBody httpBody = new HttpBody();
        if (isAddUserId) {
//            httpBody.add(Constants.Companion.getBUNDLE_USER_ID(), AppData.Companion.getUserId());
//            httpBody.add(Constants.Companion.getBUNDLE_SHOP_ID(), AppData.Companion.getShopId());
        }
        return httpBody;
    }

    /**
     * @return
     */
    public static HttpBody getBody(boolean isAddUserId, HashMap<String, Object> map) {
        HttpBody body = getBody(isAddUserId);
        if (map != null) {
            for (String key : map.keySet()) {
                body.add(key, map.get(key));
            }
        }
        return body;
    }

}